package com.android.stockme.backend;

import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

import com.android.stockme.backend.configuration.IConfigurationChangedListener;

public class RefreshTask extends TimerTask implements IConfigurationChangedListener {
		
	/**
	 */
	public RefreshTask(IASyncComputation code, IBackendMessageQueue messageQueue, int initialDelay, int interval, String title) {
		this.code = code;
		this.messageQueue = messageQueue;
		this.initialDelay = initialDelay;
		this.interval = interval;
		this.title = title;
	}

	@Override
	public void run() {
		Log.d("StockMe", this.title + " computing");
		this.code.compute();
		Log.d("StockMe", this.title + " posting");
		this.messageQueue.post(this.code);
//		synchronized(this) {
//			Log.d("StockMe", this.title + " restarting timer");
//			this.timer.schedule(this, this.initialDelay * 1000);
//		}
		Log.d("StockMe", this.title + " exiting");
	}

	public synchronized void startRefresh() {
		if(this.timer == null){
			this.timer = new Timer(this.title);
			this.timer.schedule(this, this.initialDelay * 1000);
		}		
	}

	public synchronized void stopRefresh() {
		this.cancel();
		this.timer.cancel();
		this.timer.purge();
		this.timer = null;		
	}
	
	public void notifyConfigurationChanged(Object arg) {
//		if (this.timer != null)
//			// Stop refreshing
//			this.stopRefresh();
		
		// Update the Timer scheduling parameters
		synchronized(this) {
			this.initialDelay = (Integer)arg;
			this.interval = (Integer)arg;			
		}

//		// Start refreshing
//		if (this.timer == null)	
//			this.startRefresh();
	}

	/**
	 * @uml.property  name="messageQueue"
	 * @uml.associationEnd  multiplicity="(1 1)" inverse="refreshTask:com.android.stockme.backend.IBackendMessageQueue"
	 */
	private IBackendMessageQueue messageQueue = null;
	private int initialDelay = 0;
	private int interval = 0;
	private IASyncComputation code = null;
	private String title = null;
	private Timer timer = null;
}
